package com.shut.vehicle.configuration;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeVehicleLicenseResponse;
import com.aliyun.tea.TeaException;
import com.shut.vehicle.exception.ServiceException;
import com.shut.vehicle.pojo.CarNum;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 卢斌
 */
public class AlibabaOcr {

    private final static Client DRIVER_CAR = createClient();

    public static CarNum releaseCarNum(MultipartFile file) {
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream;
        try {
            bodyStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        com.aliyun.ocr_api20210707.models.RecognizeVehicleLicenseRequest recognizeVehicleLicenseRequest = new com.aliyun.ocr_api20210707.models.RecognizeVehicleLicenseRequest()
                .setBody(bodyStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeVehicleLicenseResponse response = DRIVER_CAR.recognizeVehicleLicenseWithOptions(recognizeVehicleLicenseRequest, runtime);
            if (Integer.valueOf(200).equals(response.getStatusCode())) {
                String bodyValue = JSON.toJSONString(response.getBody().getData());
                StringBuilder bodyInner = new StringBuilder(bodyValue.replaceAll("\\\\", ""));
                bodyInner.deleteCharAt(bodyInner.length() - 1).deleteCharAt(0);
                JSONObject bodyObj = JSON.parseObject(bodyInner.toString());
                JSONObject data = bodyObj.getJSONObject("data");
                JSONObject face = data.getJSONObject("face");
                if (face == null || face.isEmpty()) {
                    throw new ServiceException("请上传行驶证正面照片");
                }
                JSONObject centerValue = face.getJSONObject("data");
                CarNum carNum = new CarNum();
                carNum.setCarNum(centerValue.getString("licensePlateNumber"));
                carNum.setBrand(centerValue.getString("model"));
                carNum.setDetailInfo(centerValue);
                return carNum;
            } else {
                return null;
            }
        } catch (TeaException error) {
            throw new ServiceException("无法识别您的行驶证正面照");
        } catch (Exception error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
        }
        return null;
    }


    /**
     * <b>description</b> :
     * <p>使用凭据初始化账号Client</p>
     * @return Client
     *
     */
    private static Client createClient() {
        // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId("LTAI5tD2JcXsCyghExyPPxhJ").setAccessKeySecret("zrRTDhViJnClvSNZvsUNwDtTFm5Ji7");
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        try {
            return new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
